import axios from './axios';

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;

// 获取异常检测任务列表的查询参数
export interface AnomalyDetectionQueryParams {
  task?: string; // 任务类型
  page: number;  // 当前页
  ps: number;    // 每页条数
  id?: string;   // ID筛选
  status?: string; // 状态筛选
  checkTime?: string; // 检测时间筛选
}

// 异常检测任务项
export interface AnomalyDetectionItem {
  id: string;
  checkType: string;
  checkRange: string;
  checkTime: string;
  status: string;
  anomalyReason?: string;
  task?: string;
}

// 异常检测任务列表响应
export interface AnomalyDetectionResponse {
  code: number;
  data: AnomalyDetectionItem[];
  total: number;
}

// 获取异常检测任务列表
export const getAnomalyDetectionList = async (params: AnomalyDetectionQueryParams): Promise<AnomalyDetectionResponse> => {
  try {
    const token = localStorage.getItem('token') || '';
    const response = await axios.post(
      `${API_BASE_URL}/-/bin.anomalyDetection.get_anomaly_detection_task`,
      params,
      {
        headers: { token }
      }
    );
    return response.data;
  } catch (error) {
    console.error('获取异常检测任务列表失败:', error);
    return {
      code: 500,
      data: [],
      total: 0
    };
  }
};

// 获取异常结果详情的查询参数
export interface AnomalyResultQueryParams {
  id: string;    // 异常检测任务ID
  page: number;  // 当前页
  ps: number;    // 每页条数
  reason?: string; // 异常原因筛选，多个用;分隔
}

// 异常结果详情项
export interface AnomalyResultItem {
  key: string;
  sequenceNo: number;
  fileName: string;
  filePath: string;
  fileSize: string;
  fileCount: number;
  actualFileCount: number;
  anomalyReason: string;
  storageLocation: string;
  operation: string;
}

// 异常结果详情响应
export interface AnomalyResultResponse {
  code: number;
  data: AnomalyResultItem[];
  total: number;
}

// 获取异常结果详情
export const getAnomalyResultById = async (params: AnomalyResultQueryParams): Promise<AnomalyResultResponse> => {
  try {
    const token = localStorage.getItem('token') || '';
    const response = await axios.post(
      `${API_BASE_URL}/-/bin.anomalyDetection.get_anomaly_result_by_id`,
      params,
      {
        headers: { token }
      }
    );
    return response.data;
  } catch (error) {
    console.error('获取异常结果详情失败:', error);
    return {
      code: 500,
      data: [],
      total: 0
    };
  }
};

// 添加异常检测任务的参数
export interface AddAnomalyDetectionParams {
  task: string; // 任务类型，多个用逗号分隔
}

// 添加异常检测任务响应
export interface AddAnomalyDetectionResponse {
  code: number;
  message?: string;
}

// 添加异常检测任务
export const addAnomalyDetectionTask = async (params: AddAnomalyDetectionParams): Promise<AddAnomalyDetectionResponse> => {
  try {
    const token = localStorage.getItem('token') || '';
    const response = await axios.post(
      `${API_BASE_URL}/-/bin.anomalyDetection.add_anomaly_detection_task`,
      params,
      {
        headers: { token }
      }
    );
    return response.data;
  } catch (error) {
    console.error('添加异常检测任务失败:', error);
    return {
      code: 500,
      message: '添加异常检测任务失败'
    };
  }
};

// 导出异常结果的参数
export interface DownloadAnomalyResultParams {
  id: string;    // 异常检测任务ID
  reason?: string; // 异常原因筛选，多个用;分隔
}

// 导出异常结果
export const downloadAnomalyResult = async (params: DownloadAnomalyResultParams): Promise<void> => {
  try {
    const token = localStorage.getItem('token') || '';
    const response = await axios.post(
      `${API_BASE_URL}/-/bin.anomalyDetection.download_anomaly_result`,
      params,
      {
        headers: { token },
        responseType: 'blob'
      }
    );

    // 处理文件下载
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', `异常结果_${params.id}_${new Date().getTime()}.xlsx`);
    document.body.appendChild(link);
    link.click();
    link.remove();
    window.URL.revokeObjectURL(url);
  } catch (error) {
    console.error('导出异常结果失败:', error);
    throw error;
  }
};